package com.demon.auto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demon.auto.dao.UserClientRelationDao;
import com.demon.auto.model.entity.UserClientRelationEntity;
import com.demon.auto.service.UserClientRelationService;
import com.demon.auto.utils.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户-客户端关联
 *
 * @version 1.0
 * @author huangrz
 * @date 2025/02/13 17:08
 */
@Service
public class UserClientRelationServiceImpl extends ServiceImpl<UserClientRelationDao, UserClientRelationEntity> implements UserClientRelationService {

    @Override
    public List<UserClientRelationEntity> getUserClientRelationInfo(Long userId) {
        LambdaQueryWrapper<UserClientRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserClientRelationEntity::getUserId, userId);
        return list(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveUserClientRelationInfo(Long clientId, Long userId, String alias) {
        if (clientId == null) {
            log.error("[saveUserClientRelationInfo] 客户端ID为空！");
            return false;
        }
        if (userId == null) {
            userId = CommonUtil.getCurrentUserId();
        }
        LambdaQueryWrapper<UserClientRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserClientRelationEntity::getClientId, clientId);
        queryWrapper.eq(UserClientRelationEntity::getUserId, userId);
        UserClientRelationEntity clientRelation = getOne(queryWrapper, false);
        if (clientRelation != null) {
            // 判断别名是否一致，不一致则更新
            if (!StringUtils.defaultString(clientRelation.getAlias()).equals(StringUtils.defaultString((alias)))) {
                LambdaUpdateWrapper<UserClientRelationEntity> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.set(UserClientRelationEntity::getAlias, alias)
                        .eq(UserClientRelationEntity::getId, clientRelation.getId());
                return update(updateWrapper);
            }
            return true;
        }

        // 新增关联信息
        return save(new UserClientRelationEntity()
                .setClientId(clientId)
                .setUserId(userId)
                .setAlias(alias));
    }

    @Override
    public int deleteByUserClientId(Long clientId, Long userId) {
        return baseMapper.deleteByUserClientId(clientId, userId);
    }

    @Override
    public int deleteUserClientAllRelation(Long clientId) {
        return baseMapper.deleteUserClientAllRelation(clientId);
    }

}
